package com.jiezheng.huinong.biz;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.poifs.filesystem.POIFSFileSystem;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.DateUtil;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;

import com.jiezheng.huinong.constant.FileBizType;

public class ExcelFileParser {

	private Sheet sheet;
	private Row row;

	private int dataStartRow = 0;
	private int dataEndRow = 0;
	private int dataStartCol = 0;
	private int dataEndCol = 0;
	private int sheetNum = 0;
	private FileBizType fileType = FileBizType.PEOPLE;

	/**
	 * 初始化读取方式
	 * 
	 * @param path
	 * @throws FileNotFoundException
	 */
	ExcelFileParser(String path, FileBizType fileType)
			throws FileNotFoundException {
		File file = null;
		InputStream is = null;
		POIFSFileSystem fs = null;
		Workbook wb = null;
		try {
			file = new File(path);
			is = new FileInputStream(file);
			fs = new POIFSFileSystem(is);
			wb = new HSSFWorkbook(fs);
		} catch (IOException e) {
			System.out.println("file type or file is error");
		} finally {
			if (is != null) {
				try {
					is.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}

		}

		// 初始化
		sheet = wb.getSheetAt(sheetNum);
		setReadConfig();
	}

	/**
	 * 读取Excel数据内容
	 * 
	 * @param InputStream
	 * @return Map 包含单元格数据内容的Map对象
	 */
	public Map<Integer, ArrayList<String>> getContent() {
		Map<Integer, ArrayList<String>> content = new HashMap<Integer, ArrayList<String>>();
		for (int i = dataStartRow; i <= dataEndRow; i++) {
			row = sheet.getRow(i);
			List<String> fields = processRow(row);
			content.put(i, (ArrayList<String>)fields);
		}
		return content;
	}

	/**
	 * 根据文件类型设置读取的参数
	 */
	private void setReadConfig() {
		if (fileType == FileBizType.PEOPLE) {
			setDataRow(1, 2);
			setDataCol(0, 7);
		} else if (fileType == FileBizType.APPLY) {
			setDataRow(1, 2);
			setDataCol(0, 7);
		} else if (fileType == FileBizType.INDEX) {
			setDataRow(1, 2);
			setDataCol(0, 12);
		}

	}

	/**
	 * 设置读取的行范围
	 */
	private void setDataRow(int start, int end) {
		int maxRow = sheet.getLastRowNum();

		start = Math.max(0, start);
		dataStartRow = Math.min(start, maxRow);

		end = Math.max(0, end);
		dataEndRow = Math.max(end, maxRow);
	}

	/**
	 * 设置读取的列范围
	 */
	private void setDataCol(int start, int end) {

		Row _row = sheet.getRow(0);
		int maxCol = _row.getPhysicalNumberOfCells();

		start = Math.max(0, start);
		dataStartCol = Math.min(start, maxCol);

		end = Math.max(0, end);
		dataEndCol = Math.max(end, maxCol);
	}

	/**
	 * 根据Cell类型设置数据
	 * 
	 * @param cell
	 * @return
	 */
	private String getCellFormatValue(Cell cell) {
		String cellvalue = "";
		if (cell != null) {
			// 判断当前Cell的Type
			switch (cell.getCellType()) {
			// 如果当前Cell的Type为NUMERIC
			case Cell.CELL_TYPE_NUMERIC:
			case Cell.CELL_TYPE_FORMULA: {
				// 判断当前的cell是否为Date
				if (DateUtil.isCellDateFormatted(cell)) {
					// data格式是不带带时分秒的：2011-10-12
					Date date = cell.getDateCellValue();
					SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
					cellvalue = sdf.format(date);

				}
				// 如果是纯数字
				else {
					// 取得当前Cell的数值
					cellvalue = String.valueOf(cell.getNumericCellValue());
				}
				break;
			}
			// 如果当前Cell的Type为STRIN
			case Cell.CELL_TYPE_STRING:
				// 取得当前的Cell字符串
				cellvalue = cell.getRichStringCellValue().getString().trim();
				break;
			// 默认的Cell值
			default:
				cellvalue = "";
			}
		} else {
			cellvalue = "";
		}
		return cellvalue;

	}

	/**
	 * 处理每一行的数据
	 * 
	 * @return
	 */
	private List<String> processRow(Row row) {
		List<String> rowData = new ArrayList<String>();
		int col = 0;
		try {
			for (col = dataStartCol; col <= dataEndCol; col++) {
				Cell cell = row.getCell((short) col);
				if (cell == null) {
					rowData.add("");
					continue;
				}
				rowData.add(getCellFormatValue(cell).trim());
			}
		} catch (Exception e) {
			System.out.println("processData fail, column number is: " + col );
		}

		return rowData;
	}

}
